import os
from datetime import datetime
from sqlite3 import IntegrityError

from django.contrib.auth import authenticate
from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
# apps/accounts/views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework import status

# 下面是验证码相关的导入
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
# from captcha.helpers import captcha_valid

from apps.accounts.models import CustomUser  # 假设你有自定义用户模型

import hashlib

def is_captcha_valid(captcha_key, captcha_value):
    try:


        # 获取对应的 CaptchaStore 实例
        store = CaptchaStore.objects.get(hashkey=captcha_key)

        # 打印存储的 response 和用户输入以便对比
        stored_response = store.response.lower()  # 将存储的验证码转换为小写
        user_input = captcha_value.lower()  # 将用户输入转换为小写

        # 验证验证码
        if stored_response == user_input:
            return True
        else:

            return False

    except ObjectDoesNotExist:

        return False
    except Exception as e:
        return False

@api_view(['POST'])
def login(request):
    username = request.data.get('username')
    password = request.data.get('password')
    captcha_key = request.data.get('captcha_key')
    captcha_value = request.data.get('captcha_value')
    if not username or not password:
        return Response({'message': '用户名或密码不能为空!'}, status=status.HTTP_400_BAD_REQUEST)

    user = authenticate(identifier=username, password=password)

    if not captcha_key or not captcha_value:
        return Response({'message': '请输入验证码'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证验证码
    if not is_captcha_valid(captcha_key, captcha_value):
        return Response({'message': '验证码错误'}, status=status.HTTP_400_BAD_REQUEST)
    if user is not None:
        refresh = RefreshToken.for_user(user)
        return Response({
            'message': '登录成功',
            'access_token': str(refresh.access_token),
            'refresh_token': str(refresh),
            'username': str(username)
        }, status=status.HTTP_200_OK)
    else:
        return Response({'message': '用户名或密码错误!'}, status=status.HTTP_401_UNAUTHORIZED)

import random
import string


def generate_unique_hashkey():
    while True:
        # 使用更长的随机序列以降低碰撞概率
        random_bytes = os.urandom(20)
        hashkey = hashlib.sha1(random_bytes).hexdigest()
        if not CaptchaStore.objects.filter(hashkey=hashkey).exists():
            return hashkey



@api_view(['GET'])
def get_captcha(request):
    challenge_length = 4  # 增加验证码长度以提高安全性
    challenge = ''.join(random.choices(string.ascii_letters + string.digits, k=challenge_length))

    hashkey = generate_unique_hashkey()

    try:
        store = CaptchaStore.objects.create(challenge=challenge.lower(), response=challenge.lower(), hashkey=hashkey)
        data = {
            'key': store.hashkey,
            'image_url': request.build_absolute_uri(captcha_image_url(store.hashkey))  # 返回绝对 URL
        }
        print(data)
        return Response(data)
    except IntegrityError as e:
        print(f"An integrity error occurred: {e}")
        return get_captcha(request)  # 如果发生完整性错误，重新调用此函数以生成新的验证码


def captcha_refresh(request):
    # 同样生成新的验证码文本内容，格式和长度等可根据实际要求调整
    new_challenge_length = 4
    new_challenge = ''.join(random.choices(string.ascii_letters + string.digits, k=new_challenge_length))
    new_hashkey = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()
    try:
        # 删除旧的验证码记录（如果之前有存储在数据库等地方，这里假设按 hashkey 来查找删除）
        old_key = request.GET.get('old_key')  # 尝试从前端请求参数中获取旧的验证码标识，用于删除旧记录
        if old_key:
            CaptchaStore.objects.filter(hashkey=old_key).delete()

        # 创建新的验证码记录并存储
        new_store = CaptchaStore.objects.create(challenge=new_challenge.lower(), response=new_challenge.lower(), hashkey=new_hashkey)
        data = {
            'key': new_store.hashkey,
            'image_url': request.build_absolute_uri(captcha_image_url(new_store.hashkey))
        }
        return JsonResponse(data)
    except:
        return JsonResponse({'error': '刷新验证码失败'}, status=500)